import {Component, OnInit} from '@angular/core';
import {AuthService} from '../../_services/auth.service';
import {HttpErrorResponse} from '@angular/common/http';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {MsgResponse} from '../../_models/response';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {


  validateForm: FormGroup;


  constructor(private fb: FormBuilder, private authService: AuthService) {
  }

  updateConfirmValidator() {
    /** wait for refresh value */
    setTimeout(_ => {
      this.validateForm.controls['pass_repeat'].updateValueAndValidity();
    });
  }

  confirmationValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return {required: true};
    } else if (control.value !== this.validateForm.controls['password'].value) {
      return {confirm: true, error: true};
    }
  }

  _submitForm() {
    for (const i in this.validateForm.controls) {
      if (this.validateForm.controls.hasOwnProperty(i)) {
        this.validateForm.controls[i].markAsDirty();
      }
    }
    this._register();
  }

  ngOnInit() {
    this.validateForm = this.fb.group({
      email: [null, [Validators.email]],
      username: [null, [Validators.required, Validators.minLength(6), Validators.maxLength(16)]],
      password: [null, [Validators.required, Validators.minLength(6), Validators.maxLength(16)]],
      pass_repeat: [null, [Validators.required, this.confirmationValidator]]
    });
  }

  getFormControl(name) {
    return this.validateForm.controls[name];
  }

  _register() {
    console.log(this.validateForm.value);
    this.authService.doRegister(this.validateForm.value).subscribe(
      (data: MsgResponse) => {
        console.log(data);
        if (data.StatusOk) {
          this.authService.jwtToken = data.Msg;
        } else {
          console.log(data.Msg);
        }
      },
      (err: HttpErrorResponse) => {
        console.log(err.error);
      }
    );
  }
}

